package com.bsj.sipgateway.sip.transmit.response.impl;

import com.bsj.power.common.config.redis.RedisConstant;
import com.bsj.power.common.def.entity.gb28181.Device;
import com.bsj.power.common.def.entity.log.CmdLog;
import com.bsj.power.common.def.enums.CmdLogEnum;
import com.bsj.power.common.mapper.CmdLogMapper;
import com.bsj.power.common.mapper.DeviceMapper;
import com.bsj.sipgateway.config.SipConfig;
import com.bsj.sipgateway.mq.producer.CommandUpProducer;
import com.bsj.sipgateway.sip.SipLayer;
import com.bsj.sipgateway.sip.bean.Command;
import com.bsj.sipgateway.sip.session.CallIdManager;
import com.bsj.sipgateway.sip.session.CommandManager;
import com.bsj.sipgateway.sip.session.VideoStreamSessionManager;
import com.bsj.sipgateway.sip.transmit.response.ISIPResponseProcessor;
import gov.nist.javax.sip.header.CallID;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.bsj.JedisClusterBSJ;

import javax.sip.ResponseEvent;
import javax.sip.header.ViaHeader;
import javax.sip.message.Response;
import java.util.Date;

/**
 * @author bsj-chenjunkang
 * @Description: BYE请求响应器
 * @date 2022/8/24
 */
@Component
@Slf4j
public class ByeResponseProcessor implements ISIPResponseProcessor {

    @Autowired
    private VideoStreamSessionManager streamSession;
    @Autowired
    private CommandUpProducer commandUpProducer;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private CmdLogMapper cmdLogMapper;
    @Autowired
    private JedisClusterBSJ jedisClusterBSJ;

    /**
     * 处理BYE响应
     *
     * @param evt
     * @param layer
     * @param config
     */
    @Override
    public void process(ResponseEvent evt, SipLayer layer, SipConfig config) {
//        log.info("收到bye响应");
        try {
            Response response = evt.getResponse();

            ViaHeader viaHeader = (ViaHeader) response.getHeader(ViaHeader.NAME);
            CallID callID = (CallID) response.getHeader(CallID.NAME);

            int statusCode = response.getStatusCode();
//            jedisClusterBSJ.set("WAITING_REPLY_CALLID" + callIdHeader.getCallId(), deviceId + "_" + did + "_" + channelSerial);
            String str = jedisClusterBSJ.get(RedisConstant.WAITING_REPLY_CALLID + callID.getCallId());
            if (str != null && 200 == statusCode) {
                String[] s = str.split("_");
                if (s.length == 3) {
                    String deviceId = s[0];
                    String did = s[1];
                    String channelSerial = s[2];
                    log.info("收到设备bye的回复，status=200，删除redis中直播的状态，Call-ID={},deviceId={}", callID.getCallId(), deviceId);
                    jedisClusterBSJ.hdel(RedisConstant.VIDEO_PLAY_STATUS, did + "-" + channelSerial);
                    jedisClusterBSJ.del(RedisConstant.WAITING_REPLY_CALLID + callID.getCallId());
                }
            }

            String deviceId = CallIdManager.getDeviceId(callID.getCallId());
            if (null == deviceId) {
                log.info("bye响应没有找到deviceId");
                return;
            }
//            Device device = DeviceCache.getDevice(deviceId);
            Device device = deviceMapper.getDeviceByDeviceId(deviceId);
            Long did = device.getId();
            Command cache = CommandManager.get(deviceId, viaHeader.getBranch());
//            log.info("收到bye数据，did，{}，deviceId：{}，branch：{}", did, deviceId, viaHeader.getBranch());
            if (null != cache) {
//                log.info("cache:{}", cache.toString());
//                String sessionType = cache.getSessionType();
//                //获取需要关闭的端口，告诉流媒体
//                VideoStreamSession session = streamSession.get(deviceId, sessionType, cache.getChannel());
//                //从缓存中删除会话
//                streamSession.remove(deviceId, sessionType, cache.getChannel());
//                log.info("删除会话session：deviceId:{},type:{},channel:{}", deviceId, sessionType, cache.getChannel());
                CommandManager.remove(deviceId, viaHeader.getBranch());
//                log.info("删除command，deviceId:{}，branch：{}", deviceId, viaHeader.getBranch());
            } else {
                log.info("收到bye响应时无法获取到cache，deviceId：{}，branch：{}", deviceId, viaHeader.getBranch());
            }

            // 指令收发记录
            CmdLog cmdLog = new CmdLog();
            cmdLog.setDeviceId(device.getDeviceId());
            cmdLog.setDeviceName(device.getNickName());
            cmdLog.setTime(new Date());
            if (cache != null) {
                int cmdType = cache.getCmdType();
                String desc = null;
                if (cmdType == 0) {
                    desc = CmdLogEnum.TYPE_PLAY_CLOSE.getDesc();
                } else if (cmdType == 1) {
                    desc = CmdLogEnum.TYPE_PLAY_BACK_CLOSE.getDesc();
                }
                log.info("[" + desc + "]，收到设备响应200消息，关闭指令流程结束，deviceId=" + device.getDeviceId());
                cmdLog.setType(desc);
            }
            cmdLog.setState(CmdLogEnum.STATE_RECEIVE.getDesc());
            cmdLog.setContent("设备响应statusCode=" + response.getStatusCode() + "message=" + response.getReasonPhrase());
            cmdLogMapper.insert(cmdLog);


        } catch (Exception e) {
            log.error("处理bye响应失败", e);
        }

    }

}
